package com.flyme.module.base.provider.apiPc;


import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.flyme.common.core.model.ResultBody;
import com.flyme.common.core.model.query.CriteriaQuery;
import com.flyme.common.core.model.query.PagerInfo;
import com.flyme.common.core.model.query.PqGrid;
import com.flyme.common.core.security.OpenHelper;
import com.flyme.common.core.security.OpenUserAuth;
import com.flyme.common.core.utils.ApiAssert;
import com.flyme.common.core.utils.ObjectUtils;
import com.flyme.core.base.supper.controller.BaseController;
import com.flyme.core.base.supper.entity.EntityMap;
import com.flyme.module.base.client.constants.BaseConstants;
import com.flyme.module.base.client.entity.*;
import com.flyme.module.base.provider.service.*;
import com.flyme.module.exam.client.entity.BusAbility;
import com.flyme.module.exam.provider.service.BusAbiltityService;
import com.flyme.module.file.client.entity.SysCourse;
import com.flyme.module.file.provider.service.SysCataLogService;
import com.flyme.module.file.provider.service.SysCourseCommentService;
import com.flyme.module.file.provider.service.SysCourseService;
import com.flyme.module.file.provider.service.SysOffCourseService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 *
 *
 * @author flyme
 */
@Slf4j
@Api(tags = "pc能力测评管理")
@RestController
@RequestMapping("/pcAbility")
public class PcApiAbilityController extends BaseController<BusAbiltityService, BusAbility> {

    @Autowired
    private BusAbiltityService abilityService;
    @Autowired
    private SysEducationService educationService;
    @Autowired
    private SysBuyrecordService sysbuyrecordService;
    @Autowired
    private  SysVipService vipService;
    @Autowired
    private SysColleconService colleconService;
    @Autowired
    private SysChargeconfigService chargeconfigService;
    @Autowired
    private SysBalanceService balanceService;
    @Autowired
    private SysCourseCommentService commentService;
    @Autowired
    private SysQuestionService questionService;
    @Autowired
    private SysIntegralrecordService integralrecordService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysPushCourseService pushcourseService;
    @Autowired
    private SysUsersturecordService usersturecordService;
    @Autowired
    private SysComplanService complanService;
    @Autowired
    private SysOffCourseService sysOffCourseService;
    @Autowired
    private SysCataLogService catalogService;
    @Autowired
    private SysCourseService courseService;
    @Autowired
    private SysDeptService deptService;
    @Autowired
    private SysUsercertificateService usercertificateService;

    /** yes
     * 人才能力测评页面
     * isBuy 1已购买2为购买
     */
    @PostMapping(value = "/abilityPageWeb")
    public ResultBody abilityPageWeb(){
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        EntityMap map = new EntityMap();
        BusAbility ability = abilityService.list().get(0);
        Integer educationNum = educationService.countByUserId(openUserAuth.getUserId());
        map.put("education", educationNum);
        map.put("ability", ability);
        Integer vip = vipService.isVip(openUserAuth.getUserId());
        if(vip>0){
            map.put("isBuy", 1);
        }else{
            //查询用户是否购买过能力测评
            Integer record = sysbuyrecordService.findByUser(openUserAuth.getUserId());
            map.put("isBuy", record);
        }
        return ResultBody.success(map);
    }

    /**yes
     * 批量删除收藏
     */
    @PostMapping(value = "/delColleconWeb")
    public ResultBody delColleconWeb(String ids) {
        ApiAssert.notNull("参数不能为空", ids);
        String[] idList = ids.split(",");
        for(String id : idList){
            boolean flag = colleconService.removeById(id);
        }
        return ResultBody.ok("删除成功");
    }


    /**yes
     * 余额充值配置表
     */
    @PostMapping(value = "/chargeconfigWeb")
    public ResultBody chargeconfigWeb( Integer type) {
        ApiAssert.notNull("参数不能为空", type);
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        EntityMap map = new EntityMap();
        List<SysChargeconfig> lists = chargeconfigService.selectByType(type);
        map.put("lists", lists);
        SysBalance balance = balanceService.findByUser(openUserAuth.getUserId());
        map.put("studyCoinAmount", balance.getAmount());
        return ResultBody.success(map);
    }


    /**yes
     * 我的积分记录
     */
    @PostMapping(value = "/myIntegralRecordWeb")
    public ResultBody myIntegralRecordWeb(PagerInfo pagerInfo){
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        EntityMap map = new EntityMap();
        SysBalance balance = balanceService.getById(openUserAuth.getUserId());
        map.put("integral", balance.getIntegral());
        PqGrid pq = integralrecordService.selectByUserWeb(String.valueOf(openUserAuth.getUserId()), pagerInfo);
        map.put("records", pq);
        return ResultBody.success(map);
    }

    /**yes
     * 我的计划页面
     */
    @PostMapping(value = "/myPlanPageWeb")
    public ResultBody myPlanPageWeb(PagerInfo pagerInfo){
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        SysUser accountInfo = userService.getById(openUserAuth.getUserId());
        EntityMap map = new EntityMap();
        PqGrid pqGrid = complanService.selectUserPlan(accountInfo.getId(), accountInfo.getCompanyId(), accountInfo.getDeptId(),pagerInfo);
        List<EntityMap> list = (List<EntityMap>)pqGrid.getRows();
        for(EntityMap pu : list){
            if(ObjectUtils.isNotEmpty(pu.get("deptIds"))){
                String[] ids = pu.get("deptIds").toString().split(",");
                List<String> deptList = deptService.selectByIds(ids);
                pu.put("deptIds", deptList);
            }else{
                pu.put("deptIds", new ArrayList<>());
            }
        }
        map.put("myPlans", pqGrid);
        return ResultBody.success(map);
    }

    /**
     * 计划详情
     */
    @PostMapping(value = "/myPlanDetail")
    public ResultBody myPlanDetail(String planId){
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        SysUser accountInfo = userService.getById(openUserAuth.getUserId());
        EntityMap map = new EntityMap();
        SysComplan plan = complanService.getById(planId);
        List<EntityMap> userCourse = new ArrayList<>();
        //计算所有课程总视频数量
        String[] courses = plan.getCourseIds().toString().split(",");
        /*Integer allNum = catalogService.countByCourseIds(courses);
        for(String course : courses){
            //计算用户该计划一共看了的视频数量
            Integer userNum = usersturecordService.countByPlan(openUserAuth.getUserId(), Long.parseLong(planId));
            BigDecimal degree = new BigDecimal(userNum.toString()).divide(new BigDecimal(allNum.toString()), 2, BigDecimal.ROUND_HALF_UP);
            Long courseId = Long.valueOf(course);
            EntityMap em = new EntityMap();
            SysCourse uc = courseService.getById(course);
            if(ObjectUtils.isNotEmpty(uc)) {
                em.put("degree", degree);
                em.put("courseTitle", uc.getCourseTitle());
                em.put("courseImage", uc.getCourseImage());
                em.put("courseCount", catalogService.countByCourseId(courseId));
                em.put("createTime", uc.getCreateTime());
                em.put("targetType", 2);
                em.put("id", planId);//计划
                em.put("courseId", course);
                userCourse.add(em);
            }
        }*/
        for (String course : courses) {
            Long courseA = Long.valueOf(course);
            //计算该课程的视频数量
            Integer allNum = catalogService.countByCourseId(courseA);
            //计算用户该计划一共看了的视频数量
            Integer userNum = usersturecordService.countByCourse(openUserAuth.getUserId(), courseA);
            BigDecimal degree = new BigDecimal(userNum.toString()).divide(new BigDecimal(allNum.toString()), 2, BigDecimal.ROUND_HALF_UP);
            Long courseId = Long.valueOf(course);
            EntityMap em = new EntityMap();
            SysCourse uc = courseService.getById(course);
            em.put("degree", degree);
            em.put("courseTitle", uc.getCourseTitle());
            em.put("courseImage", uc.getCourseImage());
            em.put("courseCount", catalogService.countByCourseId(courseId));
            em.put("createTime", plan.getCreateTime());
            em.put("targetType", 2);
            em.put("id", plan.getId());//计划
            em.put("courseId", course);
            userCourse.add(em);
        }
        map.put("myplan", userCourse);
        return ResultBody.success(map);
    }

    /**yes
     * 个人中心左侧头像
     */
    @RequestMapping(value = "/centreInfoWeb")
    public ResultBody centreInfoWeb(){
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        String loginType = userAuth.getLoginType();
        SysUser person = userService.getById(userAuth.getUserId());
        EntityMap user = userService.getEntityMap(q().eq("id", userAuth.getUserId()));
        EntityMap vip = vipService.getVipByUser(userAuth.getUserId());
        String avatar = user.get("avatar");
        String nickName = user.get("nickName");
        if (ObjectUtils.isEmpty(avatar) || BaseConstants.DEFAULT_USERHEAD.equals(avatar)) {
            if (!BaseConstants.USER_ACCOUNT_TYPE_MOBILE.equals(loginType)) {
                user.put("avatar", userAuth.getAvatar());
                user.put("avatar", userAuth.getAvatar());
            }
        }
        if (ObjectUtils.isEmpty(nickName)) {
            if (!BaseConstants.USER_ACCOUNT_TYPE_MOBILE.equals(loginType)) {
                user.put("nickName", userAuth.getNickName());
            }
        }
        user.put("vipName", "");
        user.put("vipExpiryDate", "");
        user.put("isVip", 0);
        user.put("vipCode", "");
        SysBalance balance = balanceService.findByUser(person.getId());
        user.put("studyCoin", balance.getAmount());
        //isVip:0非vip，1vip，2vip已过期
        if (ObjectUtils.isNotEmpty(vip)) {
            user.put("vipName", "VIP会员");
            user.put("vipExpiryDate", vip.get("expiryDate").toString().substring(0,10));
            user.put("isVip", 2);
            user.put("vipCode", vip.get("vipCode"));
            //判断是否已过期
            Long a = DateUtil.between(DateUtil.date(), DateUtil.parseDateTime(vip.get("expiryDate").toString()), DateUnit.MINUTE, false);
            if(a > 0){//未过期
                user.put("isVip", 1);
            }
        }
        return ResultBody.success(user);
    }

    /**
     * 根据证书编号查询证书
     * @param certificateNum
     * @return
     */
    @PostMapping(value = "/searchByNum")
    public ResultBody searchByNum(String certificateNum){
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        SysUsercertificate usercertificate = usercertificateService.getByNum(userAuth.getUserId(), certificateNum);
        return ResultBody.success(usercertificate);
    }

}
